<template>
    <el-container>
        <el-header></el-header>
        <el-main>
            <div class="content">
                <h3>购物车</h3>
                <router-link to="/" style="text-decoration-line: none;color: black;margin-top: -10px"><h4>
                    &lt;返回首页</h4></router-link>
                <div v-for="item in carts" :key="item.id" class="item_warp">
                    <div style="float: left">
                        <input type="checkbox" v-model="item.checked" @change="updateCheckedItems"/>
                    </div>
                    <div class="flex_row">
                        <div style="margin-left: 10px;margin-bottom: 10px">
                            <span style="color: black;font-weight: bolder">店铺名称： <b
                                    style="color: black;font-weight: bolder">{{ item.name }}</b></span>
                        </div>
                        <div v-for="(item2,index) in item.cartItems" :key="item2.id">
                            <div style="float: left">
                                <input type="checkbox" v-model="item2.checked" @change="updateCheckedItems1"/>
                            </div>
                            <div style="float: left">
                                <img
                                        :src="`http://127.0.0.1:8081/product/${item2.product.picture }`"
                                        class="store_icon"
                                />
                            </div>
                            <div style="padding-left: 230px" class="jianju">
                                <p><span><b
                                        style="color:darkgoldenrod">商品标题：</b>{{ item2.product.title }}</span><br>
                                </p>
                                <p><span><b style="color:darkgoldenrod">商品副标题：</b>{{
                                    item2.product.subtitle
                                    }}</span></p>
                                <span><b style="text-decoration-line: line-through;color:darkgoldenrod">原价：</b>
                                    <span style="text-decoration-line: line-through;color:red">{{
                                        item2.product.price
                                        }}</span></span><br>
                                <p><span><b style="color:darkgoldenrod">现价：</b>{{
                                    item2.product.new_price
                                    }}</span><br></p>
                                <span><b style="color:darkgoldenrod">数量：</b></span><br>
                                <el-input-number v-model="item2.number" size="large" @change="handleChange(item2)"
                                                 style="margin-left: 80px"/>
                            </div>
                            <el-divider></el-divider>
                        </div>
                    </div>
                </div>
                <div class="total">
                    <div class="total_1">
                        <el-row>
                            <el-col :span="5">
                                已选中商品数量：<span
                                    style="font-weight: bolder;color: red;font-size: 23px">{{ selectedCount }}</span>&nbsp;件
                            </el-col>
                            <el-col :span="4">
                                总价：<span
                                    style="font-weight: bolder;color: red;font-size: 23px">{{ totalPrice }}</span>&nbsp;￥
                            </el-col>
                            <el-col :span="1">
                                <el-button @click="js()" type="danger">结算</el-button>
                            </el-col>
                        </el-row>
                    </div>

                </div>

            </div>

            <el-dialog v-model="order" title="加入订单" width="380px" style="text-align: center;">
                地址： <el-select v-model="value" value-key="id" placeholder="Select">
                <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.address"
                    :value="item"
                ><span @click="selectA(item.id)">{{item.address}}</span></el-option>
            </el-select>
                <p>
                    姓  名：{{ value ? value.name: 'no select' }}
                    手机号：{{ value ? value.telephone: 'no select' }}
                    地  址：{{ value ? value.address: 'no select' }}
                </p>
                <el-form v-for="order in orders1" label-width="80px" style="width: 200px;margin: 0 auto">
                    <el-form-item>
                        <el-image style="height: 100px;width: 100px;margin-left: -30px"
                                  :src="`http://127.0.0.1:8081/product/${order.product.picture}`"/>
                    </el-form-item>
                    <el-form-item label="商品名称:">
                        {{ order.product.title }}
                    </el-form-item>
                    <el-form-item label="单价:">
                        {{ order.product.new_price }}
                    </el-form-item>
                    <el-form-item label="数量:">
                        {{ order.number }}
                    </el-form-item>
                    <el-form-item label="总价:">
                        {{totalPrice}}
                    </el-form-item>
                    <hr style="width: 300px;margin-left: -50px"/>
                </el-form>
                <el-button @click="cs()">确认订单</el-button>
            </el-dialog>
            <el-dialog v-model="zf" title="支付订单" width="350px" center>
                <el-button @click="zf1()">确认支付</el-button>
                <el-button @click="qxzf()">取消支付</el-button>
            </el-dialog>

            <el-dialog v-model="jishi" title="未支付" width="35%">
                <div>
                    <p>剩余时间{{count}}秒后自动取消订单</p>
                </div>
            </el-dialog>
        </el-main>
    </el-container>

</template>


<script lang="ts" setup>
import {ref, reactive, toRaw, onMounted, computed} from 'vue'
import cartApi from '../api/shopCarApi.js'
import orderApi from '../api/order.js'
import axios, {create} from 'axios'
import {ElMessage, ElTable} from "element-plus";
import router from '../router/index.js'
import addressApi from "../api/address";

const modifyNum = reactive({
    id: '',
    number: ''
})

const carts = ref([])
const shopCar = async () => {
    const res = await cartApi.queryProduct();
    console.log(res.data)
    carts.value = res.data
}

let handleChange = async (value) => {
    modifyNum.id = value.id
    modifyNum.number = value.number
    console.log(modifyNum.id)
    console.log(modifyNum.number)
    const res = await cartApi.modify(modifyNum)
    if (res.data) {
        console.log(res.data)
        shopCar();
    }
    if (value.number == 0) {
        await axios.delete("http://127.0.0.1:8080/cart/removeById/" + value.id)
            .then(res => {
                if (res.data) {
                    shopCar()
                }
            })
    }
}
onMounted(() => {
    shopCar()
    addresses()
})


// 响应式变量，用于存储选中商品的数量
const selectedCount = ref(0);
// #################################响应式变量，用于存储总价##########################
const totalPrice = ref(0);

// ################################监听购物车中复选框的改变######################
function updateCheckedItems() {
    for (const item of carts.value) {
        for (const item2 of item.cartItems) {
            if (item.checked) {
                item2.checked = true
                updateCheckedItems1()
            }
            if (item.checked == false) {
                item2.checked = false
                updateCheckedItems1()
            }
        }
    }
}

function updateCheckedItems1() {
    // 重新计算选中商品的数量和总价
    selectedCount.value = calculateSelectedCount();
    totalPrice.value = calculateTotalPrice();
    orderForm.orders = addOrder();
}
// ############################计算选中商品的数量#########################
function calculateSelectedCount() {
    let count = 0;
    for (const item of carts.value) {
        for (const item2 of item.cartItems) {
            if (item2.checked) {
                count += item2.number;
            }
        }
    }
    return count;
}
// ###################################计算总价##########################
function calculateTotalPrice() {
    let price = 0;
    for (const item of carts.value) {
        for (const item2 of item.cartItems) {
            if (item2.checked) {
                price += item2.number * item2.product.new_price;
                console.log(price)
            }
        }
    }
    return price;
}

function addOrder() {
    // const orderForm = reactive({
    //     orders:[]
    // })
    const arr = []

    for (const item of carts.value) {
        for (const item2 of item.cartItems) {
            if (item2.checked) {
                arr.push(item2)
            }
        }
    }
    return arr
}

const orderForm = reactive({
    orders: []
})
orderForm.orders = addOrder()

const order = ref(false)
const orders1 = ref([])
// #######################################结算#############################
const js = () => {
    orders1.value = orderForm.orders
    console.log(orders1.value)
    order.value = true
}
//###################################查询地址#######################
type Option = {
    id: number
    name: string
    telephone: string
    address: string
}
const ATForm = reactive({
    aid:''
})
const value = ref<Option>()
const options = ref([])
const addresses = async() =>{
    const res = await addressApi.queryByUid()
    options.value = res.data
}
const selectA = (aid) =>{
    ATForm.aid = JSON.stringify(aid)
    console.log(ATForm.aid)
}

// #################################确认订单########################
const cs = async () =>{
    const res = await orderApi.create2(orderForm)
    const res1 = await orderApi.modifyTAndA(ATForm)
    if (res.data && res1.data){
        console.log(res.data,res1.data)
        order.value = false
        zf.value = true
        startTimer()
    }
}
// ###############################支付###############################
const zf = ref(false)
const zf1 = async() =>{
    const res = await orderApi.modifyStaList()
    if(res.data){
        zf.value = false
        order.value = false
        alert("支付成功")
        window.location.reload()
    }
}
const jishi = ref(false)
const qxzf = () =>{
    zf.value = false
    order.value = false
    jishi.value = true
}
const count = ref(20);
let timer;

const startTimer = () => {
    timer = setInterval(() => {
        count.value--;
        if(count.value === 0){
            stopTimer()
            removeOrder()
        }
    }, 1000);

};
const stopTimer = () => {
    clearInterval(timer);
    jishi.value = false
};

const removeOrder = async () =>{
    const res = await orderApi.deleteOrderList()
    if(res.data){
        alert("订单已取消")
    }
}


</script>
<style>
body {
    background: #f5f5f5;
}
</style>
<style scoped>
.el-header {
    height: 50px;
    background-color: #545c64;
    position: relative;
}

.item_warp {
    margin-top: 20px;
    padding: 24px;
    background: #ffffff;
    height: auto;
}

.content {
    margin: 0 auto;
    width: 1080px;
}

.store_icon {
    height: 30px;
    width: 30px;
}

.shop_content {
    margin: 20px 0;
}

.content_right {
    height: 200px;
}

/*.fixed_warp {*/
/*    position: fixed;*/
/*    bottom:10px;*/
/*    left: 0;*/
/*    right: 0;*/
/*    height: 88px;*/
/*    padding: 0 20px;*/
/*    background: #ffffff;*/
/*}*/

.flex_row img {
    width: 150px;
    height: 160px;
}

.flex_row {
    height: auto;
}

.flex_row .jianju span {
    margin-top: 20px;
}

.total {
    width: 1080px;
    height: 100px;
    background-color: white;
    margin-top: 10px;
}

.total_1 {
    padding-top: 40px;
    padding-left: 20px;
    font-size: 19px;

}
</style>